package cn.caplike.demo.netty.websocket;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

/**
 * Description: 处理文本的.
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2021-11-29 13:05
 */
public class TextWebSocketFrameChannelInboundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        System.out.println("收到消息: " + msg.text());

        // 读取到消息之后, 写回去...
        ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间: " + LocalDateTime.now())); // ! 不能写 String
    }

    /**
     * 连接建立成功.
     * <br>{@inheritDoc}
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        // ~ channel 和客户端的连接
        System.out.println("handlerAdded: " + ctx.channel().id().asLongText());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelActive: " + ctx.channel().id().asLongText());
        super.channelActive(ctx);
    }

    /**
     * 连接关闭时.
     * <br>{@inheritDoc}
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        System.out.println("handlerRemoved: " + ctx.channel().id().asLongText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        System.err.println("exceptionCaught");
        ctx.close();
    }
}
